package algorithms.leaning.class01;

import common.util.MyUtil;

import java.util.Arrays;

/**
 * 在一个有序数组中，找某个数是否存在
 *
 * @author guichang
 * @date 2021/5/30
 */

@SuppressWarnings("all")
public class Code4_二分_精确查找 {

    public static void main(String[] args) {
        int[] nums = MyUtil.createRandomArray(10, 0, 20);
        Arrays.sort(nums);
        MyUtil.printInt(nums);
        int index = binarySearch(nums, 10);
        MyUtil.print(index);
    }

    public static int binarySearch(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1, mid;
        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

}